package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogParser;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Qualifier("LogParserWithParallelCxyImpl")
public class LogParseWithParallelCxyImpl implements LogParser {

    @Override
    public Map<String, List<LogItem>> parse(String folderName) {
        Map<String, List<LogItem>> resultMap = new HashMap<>();
        processDirectory(new File(folderName), resultMap);
        return resultMap;
    }

//    private void processDirectory(File directory, Map<String, List<LogItem>> resultMap) {
//        File[] files = directory.listFiles();
//        if (files != null) {
//            Arrays.stream(files).parallel().forEach(file -> {
//                if (file.isDirectory()) {
//                    processDirectory(file, resultMap);
//                } else if (file.getName().endsWith(".log")) {
//                    try {
//                        List<LogItem> logItems = parseLogFile(file.getAbsolutePath());
//                        resultMap.put(file.getAbsolutePath(), logItems);
//                    } catch (IOException e) {
//                        // 处理异常
//                        e.printStackTrace();
//                    }
//                }
//            });
//        }
//    }


    private void processDirectory(File directory, Map<String, List<LogItem>> resultMap) {
        List<File> logFiles = Arrays.stream(directory.listFiles())
                .filter(file -> file.getName().endsWith(".log"))
                .collect(Collectors.toList());

        logFiles.stream().parallel().forEach(file -> {
            try {
                List<LogItem> logItems = parseLogFile(file.getAbsolutePath());
                resultMap.put(file.getAbsolutePath(), logItems);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        List<File> subDirectories = Arrays.stream(directory.listFiles())
                .filter(File::isDirectory)
                .collect(Collectors.toList());

        subDirectories.forEach(subDir -> processDirectory(subDir, resultMap));
    }


    private List<LogItem> parseLogFile(String filePath) throws IOException {
        List<LogItem> logItems = new ArrayList<>();
        List<String> lines = Files.readAllLines(Paths.get(filePath));

        LogItemParserCxyImpl logItemParser = new LogItemParserCxyImpl();

        for (String line : lines) {
            Optional<LogItem> parsedLogItem = logItemParser.parse(line);
            parsedLogItem.ifPresent(logItems::add);
        }

        return logItems;

    }


}
